﻿using log4net;
using ServerControl.Dal;
using ServerControl.Model;
using ServerControl.Model.Enum;
using ServerControl.Utils;
using ServerControl.WebManage.Attributes;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;

namespace ServerControl.WebManage.Controllers
{
    [RoutePrefix("api")]
    public unsafe class ApiController : BaseController
    {
        private static ILog logger = LogManager.GetLogger("ApiController");
        private static readonly object onlyLock = new object();


        public string UserName
        {
            get
            {
                Dictionary<string, string> dicts = new Dictionary<string, string>();
                Request.Headers.AllKeys.ToList().ForEach(key =>
                {
                    dicts.Add(key.ToLower(), Request.Headers[key]);
                });

                if (dicts.Keys.Contains("username") && dicts["username"].Length > 0)
                {
                    return dicts["username"];
                }

                return "";
            }
        }

        // 反馈
        [Apk]
        [HttpPost]
        [Route("feedback")]
        public JsonResult FeedBack(Feedback feedback)
        {
            try
            {
                feedback.AddTime = DateTime.Now;
                feedback.UserName = UserName;
                var isSuccess = FeedbackDal.Insert(feedback);

                if (isSuccess)
                {
                    return new JsonNetResult { Data = new SuccessResult { } };
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return new JsonNetResult { Data = new FailResult { Msg = "反馈处理异常" } };
        }

        // 获取数据
        [Apk]
        [HttpPost]
        [Route("comment/get")]
        public JsonResult GetComment(string clientName)
        {
            try
            {
                Account account = null;
                var comment = CommentDal.Select(ref account, UserName, clientName);

                if (comment != null)
                {
                    var video = VideoDal.Select(UserName, comment.VideoId);

                    if (comment.ContentType == ContentTypeEnum.Image)
                    {
                        var port = Request.Url.Port;
                        comment.Content = $"{Request.Url.Scheme}://{Request.Url.Host}{(port == 80 ? "" : $":{port}")}{comment.Content}";
                    }

                    return new JsonNetResult { Data = new SuccessResult<dynamic> { Data = new { Comment = comment, Account = account, Link = video.link } } };
                }
                else
                {
                    return new JsonNetResult { Data = new SuccessResult { Msg = "无数据" } };
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return new JsonNetResult { Data = new FailResult { Msg = "获取数据异常" } };
        }

        // 反馈数据
        [Apk]
        [HttpPost]
        [Route("comment/report")]
        public JsonResult ReportComment(int id)
        {
            try
            {
                var isSuccess = CommentDal.UpdateComment(UserName, id);

                if (isSuccess)
                {
                    return new JsonNetResult { Data = new SuccessResult { } };
                }
                else
                {
                    return new JsonNetResult { Data = new FailResult { Msg = "报告结果失败" } };
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return new JsonNetResult { Data = new FailResult { Msg = "报告结果异常" } };
        }

        [Apk]
        [HttpPost]
        [Route("comment/release")]
        public JsonResult ReleaseComment(int id)
        {
            try
            {
                var isSuccess = CommentDal.Release(UserName, id);

                if (isSuccess)
                {
                    return new JsonNetResult { Data = new SuccessResult { } };
                }
                else
                {
                    return new JsonNetResult { Data = new FailResult { Msg = "释放失败" } };
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return new JsonNetResult { Data = new FailResult { Msg = "释放异常" } };
        }

        [Apk]
        [HttpPost]
        [Route("account/report")]
        public JsonResult ReportAccount(Account account)
        {
            try
            {
                account.AddTime = DateTime.Now;
                account.Cookies = string.IsNullOrEmpty(account.Cookies) ? "" : account.Cookies;
                account.UserName = UserName;
                var isSuccess = AccountDal.Insert(account);

                if (isSuccess)
                {
                    return new JsonNetResult { Data = new SuccessResult { } };
                }
                else
                {
                    return new JsonNetResult { Data = new FailResult { Msg = "上报账号信息失败" } };
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return new JsonNetResult { Data = new FailResult { Msg = "上报账号信息异常" } };
        }
    }
}